import axios from 'axios'
import qs from 'qs'
import {
	MessageBox,
	Message
} from 'element-ui'
import store from '@/store'
import {
	getToken,
	getDoorToken
} from '@/utils/auth'

import SETTING from '@/settings'

const {
	WEBAPI,
	PREAPI,
	PROXY
} = SETTING

// create an axios instance
const service = axios.create({
	proxy: PROXY,
	baseURL: PROXY ? PREAPI : WEBAPI + PREAPI, // url = base url + request url
	withCredentials: true, // send cookies when cross-domain requests
	timeout: 30 * 1000 // request timeout
})

// request interceptor
service.interceptors.request.use(
	config => {
		if (getToken()) {
			config.headers['Authorization'] = getToken()
		}
		if (getDoorToken()) {
			config.headers['DoorAuthorization'] = getDoorToken()
		}
		config.headers['Content-Type'] = 'multipart/form-data'
		return config
	},
	error => {
		// do something with request error
		console.log(error) // for debug
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	response => {
		const res = response.data
		if (response.headers['content-type'] == 'image/jpeg;charset=UTF-8') {
			return res
		} else if(response.headers['content-type'] == 'application/vnd.ms-excel;charset=UTF-8'){
			var tempRes={};
			tempRes.data=res;
			var tempName=response.headers['content-disposition'].split('filename=')[1];
			tempName=decodeURI(tempName);
			tempRes.filename=tempName;
			return tempRes;
		}
		else {
			if (res.code !== 200) {
				Message({
					message: res.message || 'error',
					type: 'error',
					duration: 5 * 1000
				})

				if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
					MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again',
						'Confirm logout', {
							confirmButtonText: 'Re-Login',
							cancelButtonText: 'Cancel',
							type: 'warning'
						}).then(() => {
						store.dispatch('user/resetToken').then(() => {
							location.reload()
						})
					})
				}
				return Promise.reject(res.message || 'error')
			} else {
				return res
			}
		}
	},
	error => {
		console.log('err' + error) // for debug
		Message({
			message: error.message ? error.message : 'error',
			type: 'error',
			duration: 5 * 1000
		})
		return Promise.reject(error)
	}
)

export default service
